package com.moonligt.designpatterns.designpatterns.Iterator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @ClassName BookShelf
 * @Description: TODO
 * @Author Moonlight
 * @Date 2020/5/16 10:34
 * @Version V1.0
 **/
public class BookShelf implements Aggregate {
	
	private List<Book> books;
	private int last = 0;
	
	public BookShelf (int bookSize) {
		this.books = new ArrayList<>(bookSize);
	}
	
	public Book getBookAtIndex(int index){
		return books.get(index);
	}
	
	public void addBook(Book book){
		if (last < books.size()) {
			books.add(book);
		} else {
			List<Book> levelUp = new ArrayList<>(books.size() * 2);
			levelUp.addAll(books);
			levelUp.add(book);
			books = levelUp;
		}
		last++;
	}
	
	public int length(){
		return last;
	}

	@Override
	public Iterator iterator() {
		return new BookShelfIterator(this);
	}
	
	public static class BookShelfIterator implements Iterator {
		
		private BookShelf bookShelf;
		private int index;
		
		public BookShelfIterator(BookShelf bookShelf){
			this.bookShelf = bookShelf;
			this.index = 0;
		}
		

		@Override
		public boolean hasNext() {
			return index < bookShelf.length();
		}

		@Override
		public Object next() {
			// TODO Auto-generated method stub
			Book book = bookShelf.getBookAtIndex(index);
			index++;
			return book;
		}
	}
}
